package com.ym.service.demo.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.ym.dao.demo.DemoDao;
import com.ym.entity.demo.Demo;
import com.ym.service.demo.DemoService;

@Service
@Transactional
public class DemoServiceImpl implements DemoService {

	@Resource
	DemoDao demoDao;

	@Override
	public Page<Demo> listPage(String keyword, Pageable pageable) {
		// return demoDao.findByNameContainingOrNicknameContaining(keyword, keyword,
		// pageable);
		// return demoDao.myListPage(keyword, pageable);
		if (pageable.getSort() == null) {
			pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort("name"));
		}
		return demoDao.findAll(new Specification<Demo>() {
			@Override
			public Predicate toPredicate(Root<Demo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Path<Integer> age = root.get("age");
				List<Predicate> list = new ArrayList<Predicate>();
				if (StringUtils.hasText(keyword)) {
					list.add(cb.or(cb.like(root.get("name"), "%" + keyword + "%"), cb.like(root.get("nickname"), "%" + keyword + "%")));
					list.add(cb.ge(age, 18));
				}
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		}, pageable);
	}

	@Override
	public List<Demo> list(String name, String nickname) {
		return demoDao.findByNameContainingOrNicknameContaining(name, nickname);
	}

	@Override
	public Demo add(Demo demo) {
		return demoDao.save(demo);
	}

	@Override
	public Demo update(Demo demo) {
		return demoDao.update(demo);
	}

	@Override
	public void delete(Demo demo) {
		demoDao.delete(demo);
	}

	@Override
	public void deleteById(String id) {
		demoDao.delete(id);
	}

}
